//
// Created by Administrator on 2017/12/10.
//
extern "C"{
#include <libavutil/mem.h>
#include <libavformat/avformat.h>
}
#include "MyPlayer.h"
#include <thread>

void MyPlayer::set_data_source(std::string input_filename){
    if(input_filename.empty()){
        return;
    }
    filename=av_strdup(input_filename.c_str());
}
void MyPlayer::prepare() {
    av_register_all();
    avformat_network_init();
    std::thread read_thread(&MyPlayer::read,this);
    read_thread.join();
}
void MyPlayer::read(){
    int err,i,ret;
    AVPacket* pkt= (AVPacket *) av_mallocz(sizeof(AVPacket));
    if(NULL==pkt){
        return;
    }
    int64_t stream_start_time;
    int64_t pkt_ts;
    int pkt_play_in_range=0;
    int std_index[AVMEDIA_TYPE_NB];
    memset(std_index,-1, sizeof(std_index));
    ic=avformat_alloc_context();
    if(!ic){
        return;
    }
    err=avformat_open_input(&ic,filename,NULL,NULL);
    if(err<0){
        release();
        return;
    }
    err=avformat_find_stream_info(ic,NULL);
    if(err<0){
        release();
        return;
    }
    realtime=is_realtime();
    for (int i = 0; i < ic->nb_streams; ++i) {
        if(ic->streams[i]->codecpar->codec_type==AVMEDIA_TYPE_VIDEO){
            std_index[AVMEDIA_TYPE_VIDEO]=i;
        }
        if(ic->streams[i]->codecpar->codec_type==AVMEDIA_TYPE_AUDIO){
            std_index[AVMEDIA_TYPE_AUDIO]=i;
        }
    }

    if(std_index[AVMEDIA_TYPE_VIDEO]>=0){

    }


}
void MyPlayer::release() {
    if(ic){
        avformat_close_input(&ic);
    }
}

bool MyPlayer::is_realtime() {
    if (ic == nullptr) return false;
    if(!strcmp(ic->iformat->name, "rtp")
       || !strcmp(ic->iformat->name, "rtsp")
       || !strcmp(ic->iformat->name, "sdp"))
        return true;

    if(ic->pb && (!strncmp(ic->filename, "rtp:", 4)
                  || !strncmp(ic->filename, "udp:", 4)))
        return 1;
    return 0;
}
int MyPlayer::stream_component_open(int stream_index){
    AVCodecContext* avct;
    AVCodec* codec;

}


